﻿// http://www.zimms.com
// Copyright (c) 2002-2007
// by James Zimmerman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/// <summary>
/// Represents a callback method to be executed by the <see cref="DynamicRule{T}"/>.
/// </summary>
/// <param name="item">The object to evaluate.</param>
/// <returns>The optionally modified instance.</returns>
/// <exception cref="EvaluationException">Thrown when an evaluatation determines <paramref name="item"/> is not acceptable.</exception>
public delegate T EvaluateCallback<T>(T item);

/// <summary>
/// Represents a dynamic rule that executes a <see cref="EvaluateCallback{T}"/> delegate.
/// </summary>
/// <example>
/// <code>
/// <![CDATA[
/// DynamicRule<String> rule = new DynamicRule<String>(x => x ?? String.Empty);
/// String value = null;
/// value = rule.Evaluate(value);
/// Debug.Assert(value != null);
/// ]]>
/// </code>
/// </example>
/// <typeparam name="T">The type to evaluate.</typeparam>
public sealed class DynamicRule<T> : IRule<T>
{
    private readonly EvaluateCallback<T> callback;

    /// <summary>
    /// Initializes a new instance of the <see cref="DynamicRule{T}"/> class with the supplied callback.
    /// </summary>
    /// <param name="callback">The callback to evaluate. This value can be <see langkeyword="null">null</see>.</param>
    public DynamicRule(EvaluateCallback<T> callback)
    {
        this.callback = callback;
    }

    /// <summary>
    /// Evaluates the supplied object optionally returning a modified instance.
    /// </summary>
    /// <remarks>
    /// <note type="implementnotes">If the </note>
    /// </remarks>
    /// <param name="item">The object to evaluate.</param>
    /// <returns>The optionally modified instance.</returns>
    public T Evaluate(T item)
    {
        return this.callback == null ? item : this.callback(item);
    }
}